<template>
  <div class="canvas-box no-select" :class="[is_mobile ? 'mobileBox' :'pcBox']">
    <div class="header no-select" :class="{havePath : !fromPath}">
      <el-page-header @back="linkToBack">
         <!-- v-if="fromPath" -->
        <template v-if="fromPath" #content>
          <div class="flex items-center header-content-box">
            <template v-if="curExhibition_name">
              <div class="relative">
                <span class="name1">{{curExhibition_name}}</span>
                <el-select v-if="exhibitionList.length > 0" class="zbselect absolute" @change="changeExhibition(1, curExhibition_id)" v-model="curExhibition_id" placeholder="请选择" size="large">
                  <el-option v-for="item in exhibitionList" :key="item.id" :label="item.exhibition_name" :value="item.id" />
                </el-select>
              </div>
              <el-icon><ArrowRight /></el-icon>
            </template>
            <template v-if="curField_name">
              <span class="name1">{{curField_name}}</span>
              <el-icon><ArrowRight /></el-icon>
            </template>
            <div class="relative">
              <span class="name1">{{curVenue_name}}</span>
              <el-select v-if="venueLists.length > 0" class="zbselect absolute" @change="changeExhibition(2, curVenue_id)" v-model="curVenue_id" placeholder="请选择" size="large">
                <el-option v-for="item in venueLists" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </div>
          </div>
        </template>
        <template #extra>
          <div class="flex item items-center list" v-if="curVenue_name != '' && !is_mobile">
            <el-button link @click="copyPath" type="primary" class="mr-2" v-if="fromPath">复制地址</el-button>
            <el-checkbox v-model="show_logo">显示logo</el-checkbox>
            <el-checkbox v-model="show_bg">显示底色</el-checkbox>
            <span class="ml-3">当前展厅搜索:</span>
            <el-input v-model="keyword" placeholder="请输入搜索内容" class="input-with-select fx1 ml-3 max-w-[400px]">
              <template #prepend>
                <el-select v-model="keyType" placeholder="请选择" style="width: 110px">
                  <el-option :label="item.name" :value="item.id" v-for="(item) in keywordList" :key="item.id" />
                </el-select>
              </template>
            </el-input>
            <el-button class="ml-2" type="primary" @click="searchSubmit">搜索</el-button>
            <el-button v-if="fromPath" @click="takeScreenshot" :loading="importData.loading">导出</el-button>
            <span class="ml-2 text-error text-[12px]">可搜索产品、展馆、展商名称</span>
            <span class="cursor-pointer ml-2" @click="changeScale(1)"><el-icon size="20"><ZoomIn /></el-icon></span>
            <span class="cursor-pointer ml-2" @click="changeScale(0)"><el-icon size="20"><ZoomOut /></el-icon></span>
            <full-screen />
          </div>
        </template>
      </el-page-header>
      
    </div>
    <div class="scroll" id="scroll" ref="scrollRef" :class="[show_bg ? '' : 'nobg', spaceDown ? 'zhua' : 'normal ']" v-loading="loading">
      <div v-if="!zgInfo && !loading" class="form-tips" style="padding:200px 0; text-align: center;">暂无数据，请切换其他进行查看</div>
      <div class="myCanvas-box" ref="contentRef" :style="{width:bgW+'px', height:bgH+'px',transform: contentRefCss.transform, transformOrigin:origin.x +' '+origin.y}">
        <div class="myCanvas-box-div" ref="myCanvasBoxDivRef">
          <img v-if="zgInfo" :src="zgInfo.image" class="canvas-bg" alt="">
          <div v-if="zgInfo" id="myCanvas" @click="onMouseDown">
            <template v-if="cardsLists.length > 0">
              <div v-for="(items, idx) in cardsLists" class="hebItem zIndex2 cursor-pointer" :key="items.id" :class="[curCheckIdx == idx ? 'on' : '', items.checked && curCheckIdx != idx ? 'on1' : '']" :style="items.booth_info.box_css">
                <div class="con-zhezhao" :data-idx="idx" data-child="1" :data-x="items.booth_info.position.x" :data-y="items.booth_info.position.y"></div>
                <div :style="items.booth_info.svg_css1" class="clip clip-black"></div>
                <div :style="items.booth_info.svg_css2" class="clip"></div>
                <template v-if="items.booth_info.text">
                  <div class="polygonData-text" :class='items.booth_info.text_class' v-if="!show_logo || !items.company_logo" :style="{ width: items.booth_info.text.width + 'px', height: items.booth_info.text.height + 'px', left: items.booth_info.text.x + 'px', top: items.booth_info.text.y + 'px',transform:'rotate('+items.booth_info.text.rotate+'deg)'}">
                    <div>
                      <div class="zwnum">{{zgInfo.name}}-{{items.booth_name}}</div>
                      <span class="zwname">{{items.short_name}}</span>
                      <div class="area flex justify-between items-center">
                        <span>{{items.booth_info.area}}㎡</span>
                        <span>{{items.company_code}}</span>
                      </div>
                    </div>
                  </div>
                </template>
                <template v-if="items.booth_info.logo && show_logo && items.company_logo">
                  <span class="logo-zwname">{{zgInfo.name}}-{{items.booth_name}}</span>
                  <div :style="{ width: items.booth_info.logo.width + 'px', height: items.booth_info.logo.height + 'px', left: items.booth_info.logo.x + 'px', top: items.booth_info.logo.y + 'px',transform:'rotate('+items.booth_info.rotate+'deg)'}" class="inner">
                    <div class="polygonData-text logo-text">
                      <img :style="{transform:'scale('+items.booth_info.logo.scale+') rotate('+items.booth_info.logo.addRotate+'deg)'}" :src="items.company_logo" alt="" crossorigin="anonymous">
                    </div>
                  </div>
                </template>
              </div>
            </template>
          </div>
        </div>
      </div>
      
    </div>
    
    <div v-if="curInfoShow">
      <popup ref="popupRef" title="展位信息详情" :async="true" width="550px" :showFooter="false">
        <div class="mb-2">参展商名称：{{curInfo && curInfo.company_name}}</div>
        <div class="mb-4" v-if="curInfo.company_products">主营业务及产品：{{curInfo.main_category_text}}：{{curInfo.company_products}}</div>
        <el-button v-if="curInfo.user_id" type="primary" @click="linkToDetail">展商详情</el-button>
      </popup>
    </div>
    
    <div v-if="searchShow" class="searchShow" :class="{is_mobile : is_mobile}">
      <div class="el-drawer__header">
        <div class="t">符合条件的展位</div>
        <el-icon size="20" @click="searchClose" class="cursor-pointer"><Close /></el-icon>
      </div>
      <div v-for="(item, index) in searchList" :key="index" @click="fixedZw(item, item.idx)" class="search-item cursor-pointer" :class="{on: curCheckIdx == item.idx}">
        {{zgInfo.name}}-{{item.booth_name}}
      </div>
    </div>
  
    
    
    
    <!-- 导出的内容 -->
    <div class="scroll" id="scroll2" :class="[show_bg ? '' : 'nobg', spaceDown ? 'zhua' : 'normal ', importData.show ? 'importShow' :'importHide']" :style="importData.show ? {width:bgW+'px', height:bgH+'px',transform: 'scale(' + importData.scale + ') translateX(-50%)'} : ''">
      <div v-if="!zgInfo && !loading" class="form-tips" style="padding:200px 0; text-align: center;">暂无数据，请切换其他进行查看</div>
      <div class="myCanvas-box" :class="{'import-text' : !show_logo}" ref="contentRef2" :style="{width:bgW+'px', height:bgH+'px'}">
        <div class="myCanvas-box-div" ref="myCanvasBoxDivRef">
          <div v-if="zgInfo && cardsLists.length > 0">
            <div v-for="(items, idx) in cardsLists" :key="items.id" class="hebItem zIndex2 cursor-pointer" :class="[curCheckIdx == idx ? 'on' : '', items.checked && curCheckIdx != idx ? 'on1' : '']" :style="items.booth_info.box_css">
              <div class="con-zhezhao" :data-idx="idx" data-child="1" :data-x="items.booth_info.position.x" :data-y="items.booth_info.position.y"></div>
              <div :style="items.booth_info.svg_css1" class="clip clip-black"></div>
              <div :style="items.booth_info.svg_css2" class="clip"></div>
              <template v-if="items.booth_info.text">
                <div class="polygonData-text" :class='items.booth_info.text_class' v-if="!show_logo || !items.company_logo" :style="{ width: items.booth_info.text.width + 'px', height: items.booth_info.text.height + 'px', left: items.booth_info.text.x + 'px', top: items.booth_info.text.y + 'px',transform:'rotate('+items.booth_info.text.rotate+'deg)'}">
                  <div>
                    <div class="zwnum">{{zgInfo.name}}-{{items.booth_name}}</div>
                    <span class="zwname">{{items.short_name}}</span>
                    <div class="area flex justify-between items-center">
                      <span>{{items.booth_info.area}}㎡</span>
                      <span>{{items.company_code}}</span>
                    </div>
                  </div>
                </div>
              </template>
              <template v-if="items.booth_info.logo && show_logo && items.company_logo">
                <span class="logo-zwname">{{zgInfo.name}}-{{items.booth_name}}</span>
                <div :style="{ width: items.booth_info.logo.width + 'px', height: items.booth_info.logo.height + 'px', left: items.booth_info.logo.x + 'px', top: items.booth_info.logo.y + 'px',transform:'rotate('+items.booth_info.rotate+'deg)'}" class="inner">
                  <div class="polygonData-text logo-text">
                    <img :style="{transform:'scale('+items.booth_info.logo.scale+') rotate('+items.booth_info.logo.addRotate+'deg)'}" :src="items.company_logo" alt="">
                  </div>
                </div>
              </template>
                          
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import FullScreen from '@/layout/default/components/header/full-screen.vue'
import { boothPreviewApi, getExhibitorBaseInfoApi,apiProductLists} from '@/api/app'
import { onMounted, onUnmounted, ref, watch } from 'vue';

const route = useRoute()
const router = useRouter()
const fromPath = route.query.fromPath || ''; // 当前的来源路径
// 返回按钮
const linkToBack = () => {
  if(fromPath && fromPath.length > 0){
    window.open(fromPath, '_self');
  }else{
    router.go(-1)
  }
  
}
const show_logo = ref(false);

// 保存未图片
import domtoimage from 'dom-to-image';
const importData = reactive({
  show:false,
  scale:1,
  loading:false
})
const takeScreenshot = async ()=> {
  importData.show = true;
  const a = boxW.value/bgW.value > 1 ? 1 : boxW.value/bgW.value;
  const b = boxH.value/bgH.value > 1 ? 1 : boxH.value/bgH.value;
  importData.scale = a > b ? b : a;
  importData.loading = true
  importImage()
}
const contentRef2 = shallowRef()
const importImage = async ()=> {
  const node = contentRef2.value;
  const dataUrl = await domtoimage.toPng(node);
  const link = document.createElement('a');
  link.download = curExhibition_name.value+'.png';
  link.href = dataUrl;
  link.click();
  importData.loading = false;
  importData.show = false
}




const cardsLists:any = ref([])
const cardsListAll:any = ref([])
const show_bg = ref(true); // 显示底色与否
const keyType = ref(route.query.code ? 2 : 1); // 搜索种类
const keywordList = ref([{id:2, name:'展商名称'}, {id:1, name:'展位号'}, {id:3, name:'产品'}]); // 搜索种类的列表 1-展位号， 2-展商名称， 3-产品
const keyword = ref(route.query.code || ''); // 搜索内容
const loading = ref(true); // 页面加载
// 查看的商家信息
const popupRef = shallowRef(); // 弹窗ref
const curInfoShow = ref(false); // 弹窗是否显示
const curInfo = ref(); // 当前查看的商家具体信息
const isDragging = ref(false)

// 顶部查询 ---------------------------------------- start ---------------------------------------- 

const searchShow = ref(false); // 查询结果弹窗是否显示
const searchList:any = ref([]); // 查询出来的数据
const searchClose = () =>{
  searchList.value = [];
  searchShow.value = false;
}

const linkToDetail = () => {
  console.log('curInfo.value', curInfo.value)
  window.open('https://www.bhdjz.com/company_detail.html?user_id='+curInfo.value.user_id, '_blank');
}

// keyType -- 1-展位号， 2-展商名称， 3-产品
const getKewords = (m:any) =>{
  console.log('v---', keyType.value , m.company_code)
  if(keyType.value === 2){
    return m.company_name && m.company_name.includes(keyword.value) || m.company_code && m.company_code.includes(keyword.value)
  }else if(keyType.value === 1){
    return m.booth_name ? m.booth_name.includes(keyword.value): false
  }else if(keyType.value === 3){
    return m.company_products ? m.company_products.includes(keyword.value) : false
  }
}
// 改变展现  unAllot 0-全部，1-'未分配'，2-'已分配'}] async 
const contentRefCss=reactive({transform:'scale(1)'})
const curCheckIdx = ref(-1); // 当前选中的一个
const searchSubmit = async () => {
  loading.value = true
  searchList.value = [];
  if(keyType.value == 3){
    boothPreviewApi({venue_id:curVenue_id.value, productName:keyword.value}).then(async (res)=>{
      console.log('res----',res)
      cardsLists.value = cardsLists.value.map((n:any) => { n.checked = false; return n })
      await res.forEach((m:any) =>{
        const j = cardsLists.value.findIndex( (n:any) => n.id === m.id)
        searchList.value.push({...cardsLists.value[j], idx: j});
        cardsLists.value[j].checked = true;
      })
      console.log('searchList.value----', searchList.value)
      searchSubmitFun()
    })
    
  }else{
    await cardsLists.value.forEach((m:any, i:number) =>{
      if( keyword.value.length > 0 && getKewords(m) ){
        searchList.value.push({...m, idx: i});
        cardsLists.value[i].checked = true;
      }else{
        cardsLists.value[i].checked = false;
      }
      
    })
    searchSubmitFun()
  }
  
  
};
const searchSubmitFun = () =>{
  if(!keyword.value) return
  console.log('搜索---', searchList.value, searchList.value.length)
  if(searchList.value.length > 1){
    searchShow.value = true;
    curCheckIdx.value = -1;
    loading.value = false;
    const index = cardsLists.value.findIndex( (m:any) => m.id === searchList.value[0].id)
    fixedZw(searchList.value[0], index)
  }else if(searchList.value.length === 1){
    const index = cardsLists.value.findIndex( (m:any) => m.id === searchList.value[0].id)
    fixedZw(searchList.value[0], index)
  }else if(searchList.value.length === 0){
    // feedback.msgError('当前内容未搜索到，请您重新输入要搜索内容')
    loading.value = false
    alert('当前内容未搜索到，请您重新输入要搜索内容')
    keyword.value = '';
  }
  
}
// 顶部查询 ---------------------------------------- end ----------------------------------------


// 定位到某一个合并展位上去
const fixedZw = (val:any, idx:number = 0) => {
  loading.value = true
  scale.value = 1;
  const x = -val.booth_info.position.x - val.booth_info.position.w/2 + window.innerWidth/2-100;
  const y = -val.booth_info.position.y - val.booth_info.position.h/2 + window.innerHeight/2-60;
  curCheckIdx.value = idx;
  wheelData.x1 = Math.floor(x);
  wheelData.y1 = Math.floor(y);
  setTimeout(()=>{
    getMatrix()
  },200)
  
  
  // scale.value = 1.5;
  // wheelData.x = -val.booth_info.position.x - val.booth_info.position.w/2 + window.innerWidth/2-100;
  // wheelData.y = -val.booth_info.position.y - val.booth_info.position.w/2 + window.innerWidth/2-100;
  // calculateOffset();
  
  
 
}

// 点击按钮放大缩小
const scaleAdd = 0.1; // 缩小差值
const changeScale = (type : number) => {
  if(type === 1){
    scale.value = scale.value + scaleAdd
  }else{
    scale.value = scale.value - scaleAdd
  }
  getMatrix()
}


const spaceDown = ref(false); // 当前是否摁下空格键

const booth = route.query.booth || ''
const exhibitionList = ref<any[]>([]);//展会列表
const curExhibition_id:any = ref(route.query.exhibition_id);//当前展会id
const curExhibition_name:any = ref(''); // 当前展会名称
const exhibition_field_name:any  = ref('') // 当前展会区域名称
const exhibition_field_id:any  = ref('') // 当前展会区域id


const venueLists = ref<any[]>([]);//场馆列表
const curVenue_id:any = ref(route.query.venue_id);//当前场馆id
const curVenue_name:any = ref(''); // 当前场馆名称
const curVenue_status:any = ref(''); // 当前场馆状态
const changeType = ref(0)

// 顶部---根据展会获取场馆列表
const curVenueInfo = ref()




// 复制地址
const copyPath = () => {
 const val = `${window.location.origin}${window.location.pathname}?venue_id=${curVenue_id.value}`
 const textarea = document.createElement('textarea');
 textarea.value = val;
 document.body.appendChild(textarea);
 textarea.select();
 document.execCommand('copy');
 document.body.removeChild(textarea);
}

// 展会基础信息
const queryParams = reactive({venue_id:''})
const curField_id = ref();
const curField_name = ref('')
const getApiExhibitionVenueListNew = async () => {
  await getExhibitorBaseInfoApi({}).then(res => {
    exhibitionList.value = res;
    if (res.length > 0) {
      let index = res.findIndex((n:any) => n.status == 1);
      index = index < 0 ? 0 : index;
      const curzhanhuiInfo = res[index];
      console.log('curzhanhuiInfo----', curzhanhuiInfo, curVenue_id.value)
      
      let curVenueItem = curVenue_id.value ? curzhanhuiInfo.venueList.find((n:any) => n.id == curVenue_id.value) : curzhanhuiInfo.venueList[0];
      console.log('curVenueItem-----------------------', curVenueItem)
      curVenueItem = curVenueItem || curzhanhuiInfo.venueList[0];
      curExhibition_name.value = curzhanhuiInfo.exhibition_name;
      curExhibition_id.value = curzhanhuiInfo.id;
      curField_id.value = curzhanhuiInfo.field_id;
      curField_name.value = curzhanhuiInfo.filed_name;
      curVenue_id.value = curVenueItem.id;
      curVenue_name.value = curVenueItem.name;
      venueLists.value = curzhanhuiInfo.venueList;
      
      console.log('顶部筛选细腻些--11111', curVenueItem)
      zgInfo.value = curVenueItem;
      queryParams.venue_id = curVenue_id.value;
      
      
      if(booth && booth.length > 0){
        keyword.value = booth;
        keyType.value = 1;
        
      }
      setCanvasInfo();
    }
  })

  
}


// 顶部---type 1-展会,2-展馆
const changeExhibition = (type:number, _id : number | string) => {
  console.log('_id------->', _id)
  changeType.value = type;
  if(type == 1){
    const item = exhibitionList.value.find((n:any) => n.id == _id)
    curExhibition_id.value = item.id;
    curExhibition_name.value = item.short_name || item.exhibition_name;
  }else{
    const item = venueLists.value.find((n:any) => n.id == _id)
    curVenue_id.value = item.id;
    curVenueInfo.value = item;
    curVenue_name.value = item.name;
    zgInfo.value = item;
    router.replace({
      name: 'Map', 
      query: { fromPath:fromPath, venue_id: curVenue_id.value, booth:booth }
    });
    getApiPreOrderLists()
  }
}
// const scrollRef = shallowRef();
const scrollRef = shallowRef(); // ref<HTMLElement | null>(null);
const contentRef = shallowRef(); // ref<HTMLElement | null>(null);
const myCanvasBoxDivRef = shallowRef(); // ref<HTMLElement | null>(null);

const data = reactive({
  show:false, // 右击操作框
  rotate:'0', // 展位选中角度
  zwW:0, // 一个展位的宽度（px）
  zwH:0, // 一个展位的高度（px）
  m_zwW:3, // 展位宽度(m)
  m_zwH:3, // 展位高度(m)
  clickDown:false, // 当前是否进行了点击
  checkedItems:ref<any[]>([]), // 选中的展位集合
  make:false, // 多个展位进行锁定
  ratio_mpx:30, // 1米等于30像素
  scroll:{left:0, top:0, offsetX:0}, // 拖拽实现滚动条对应滚动的信息存储
  
})
const boxW = ref(window.innerWidth);
const boxH = ref(window.innerHeight - 55);
const bgW = ref(0);
const bgH = ref(0);
const scale = ref(1);  // 画布缩放
const zgInfo= ref();
const setCanvasInfo = () =>{
  // console.log('setCanvasInfo-->',zgInfo.value, Number(zgInfo.value.width))
  bgW.value = Number(zgInfo.value.width)*data.ratio_mpx/1000;
  bgH.value = Number(zgInfo.value.height)*data.ratio_mpx/1000; 
  data.zwW = Number(data.m_zwW)*data.ratio_mpx;
  data.zwH = Number(data.m_zwH)*data.ratio_mpx;
  wheelData.x1 = 0;
  wheelData.y1 = 0;
  
  
  // console.log('setCanvasInfo-->',zgInfo.value, Number(zgInfo.value.width), bgW.value)
  handleResize();
}
// 监听窗口变化
const handleResize = () => {
  boxW.value = window.innerWidth;
  boxH.value = window.innerHeight;
  scale.value = boxW.value/bgW.value > 1 ? 1 : boxW.value/bgW.value;
  if(searchList.value.length > 0){
    searchSubmitFun()
  }else{
    if(is_mobile){
      translateX.value = (boxW.value - bgW.value)/2;
      translateY.value = (boxH.value - bgH.value)/2;
    }
    getMatrix()
  }
}



//根据展会获取已预订展商列表
  const getApiPreOrderLists = () => {
    console.log('获取11111111111')
    cardsLists.value = [];
    let params = {
      venue_id:curVenue_id.value
    }
    boothPreviewApi(params).then(res => {
      console.log('根据展会获取已预订展商列表', res, curExhibition_id.value)
      cardsLists.value = res;
      loading.value = false
      if(booth){
        searchSubmit()
      }
    })
    
    
  }
  
 

// 鼠标摁下的事件
const onMouseDown = (event:any) =>{
  const target = event.target as HTMLElement;
  const dataset = target.dataset;
  if(dataset && dataset.idx && !spaceDown.value){
    changeZwItem(Number(dataset.idx))
    // console.log('wo s------- ', Number(dataset.idx)) 
  }
}
// 展开某个展商的信息
const changeZwItem = async (i:number) =>{
  if(isDragging.value) return;
  curInfo.value = cardsLists.value[i];
  apiProductLists({company_id:curInfo.value.company_id}).then((res)=>{
    curInfo.value.company_products = res.lists.map((m:any)=>{return m.product_name}).toString()
  })
  // console.log('选中某个数据', curInfo.value)
  curInfoShow.value = true;
  await nextTick()
  popupRef.value?.open();
}


// 获取展位号列表
const getBoothList = async () => {
  loading.value = true
  const res = curVenueInfo.value;
  console.log('res------', res)
  zgInfo.value = res;
  curExhibition_name.value = res.exhibition.short_name || res.exhibition.exhibition_name;
  curVenue_name.value = res.name;
  curVenue_status.value = res.status
  exhibition_field_name.value = res.exhibition_field.name;
  exhibition_field_id.value = res.exhibition_field.id
  
  wheelData.x1 = 0;
  wheelData.y1 = 0;
  setCanvasInfo();
  
}




// 滚轮事件下的数据
const wheelData = reactive({
  x:0, // 鼠标落下的x
  y:0, // 鼠标落下的x
  scaleAdd:1, // 缩放前和缩放后的差值
  x1:0, // 缩放后的偏移量X
  y1:0 // 缩放后的偏移量Y
})
function calculateOffset() {
  const { x, y, scaleAdd} = wheelData
  const dx = x * scaleAdd; // 计算水平方向上的偏移量
  const dy = y * scaleAdd; // 计算垂直方向上的偏移量
  wheelData.x1+= dx;
  wheelData.y1+= dy
  getMatrix()
}
const getMatrix = () => {
  
  if(!is_mobile){
    contentRefCss.transform = `matrix(${scale.value.toFixed(4)}, 0, 0, ${scale.value.toFixed(4)}, ${wheelData.x1.toFixed(2)}, ${wheelData.y1.toFixed(2)})`;
  }else{
    contentRefCss.transform = `translate(${translateX.value.toFixed(2)}px,${translateY.value.toFixed(2)}px) scale(${scale.value.toFixed(4)})`;
  }
  loading.value = false
}

// 使用提供的数据调用函数
// 初始化手势处理函数
const is_mobile = navigator.userAgent.match(/(iPad|Android|ios|iPhone)/i);
const translateX = ref(0);
const translateY = ref(0);
let initialDistance = 0;
let initialScale = 1;
let initialTranslateX = 0;
let initialTranslateY = 0;
let initialTouches : Touch[] = [];
let origin = reactive(is_mobile ? {x:'50%', y:'50%'} : {x:'0px', y:'0px'}); // 缩放的中心点
const initGestureHandlers = () => {
  if (!scrollRef.value) return;
  const handleTouchStart = (event: TouchEvent) => {
    console.log('handleTouchStart----', event)
    if (event.touches.length === 1) {
      // 记录单个触摸点的位置
      initialTouches = [event.touches[0]];
      initialTranslateX = translateX.value;
      initialTranslateY = translateY.value;
    } else if (event.touches.length === 2) {
      // 记录开始时的手指间的距离
      initialDistance = getDistance(event.touches[0], event.touches[1]);
      initialScale = scale.value;
      initialTouches = [event.touches[0], event.touches[1]];
      
      getCenterPoint(event.touches[0], event.touches[1]);
       
    }
  };

  const handleTouchMove = (event: TouchEvent) => {
    console.log('handleTouchMove----', event)
    if (event.touches.length === 1 && initialTouches.length === 1) {
      // 单个触摸点，处理移动
      const currentTouch = event.touches[0];
      const initialTouch = initialTouches[0];
      const deltaX = currentTouch.clientX - initialTouch.clientX;
      const deltaY = currentTouch.clientY - initialTouch.clientY;
      translateX.value = (initialTranslateX + deltaX);
      translateY.value = initialTranslateY + deltaY;
      setTransform()
    } else if (event.touches.length === 2 && initialTouches.length === 2) {
      // 两个触摸点，处理缩放
      const currentDistance = getDistance(event.touches[0], event.touches[1]);
      const distanceDifference = currentDistance - initialDistance;
      const _scale = initialScale + distanceDifference / 30; // 你可以调整这个系数以适应不同的缩放速度
      
      scale.value = _scale < minScale ? minScale : _scale; 
      setTransform()
    }
  };

  const handleTouchEnd = () => {
    initialTouches = [];
  };
  // 计算两个点的距离
  const getDistance = (touch1 : Touch, touch2 : Touch) : number => {
    const dx = touch1.clientX - touch2.clientX;
    const dy = touch1.clientY - touch2.clientY;
    return Math.sqrt(dx * dx + dy * dy);
  };
  // 计算中心点
  const getCenterPoint = (touch1: Touch, touch2: Touch) => {
    const centerX = (touch1.clientX + touch2.clientX) / 2-translateX.value;
    const centerY = (touch1.clientY + touch2.clientY) / 2-translateY.value;
    origin.x = `${centerX.toFixed(2)}px`;
    origin.y = `${centerY.toFixed(2)}px`;
  };
  const setTransform = () => {
    contentRefCss.transform = `translate(${translateX.value.toFixed(2)}px, ${translateY.value.toFixed(2)}px) scale(${scale.value.toFixed(2)})`
  }

  scrollRef.value.addEventListener('touchstart', handleTouchStart, { passive: true });
  scrollRef.value.addEventListener('touchmove', handleTouchMove);
  scrollRef.value.addEventListener('touchend', handleTouchEnd);
  
  // 清理事件监听器
  onBeforeUnmount(() => {
    scrollRef.value?.removeEventListener('touchstart', handleTouchStart);
    scrollRef.value?.removeEventListener('touchmove', handleTouchMove);
    scrollRef.value?.removeEventListener('touchend', handleTouchEnd);
  });
};




const minScale = 0.1;
onMounted( async () => {
  await getApiExhibitionVenueListNew();
  getApiPreOrderLists();
  console.log('is_mobile---', is_mobile)
  if (contentRef.value && !is_mobile) {
    
    console.log('aaa', contentRef.value.getBoundingClientRect())
    contentRef.value.addEventListener('wheel', (event:any) => {
      if(importData.show) return 
      const childItem = event.target.dataset;
      event.preventDefault();
      wheelData.x = (childItem.child ? Number(childItem.x) : 0) + event.offsetX;
      wheelData.y = (childItem.child ? Number(childItem.y) : 0) + event.offsetY;
      const delta = event.deltaY < 0 ? 1 : -1;
      scale.value += delta * scaleAdd;
      if (scale.value < minScale) {
        scale.value = minScale;
      }else{
        wheelData.scaleAdd = -(delta * scaleAdd)
        calculateOffset();
      }
    }, { passive: false } );
    let offsetX = 0;
    let offsetY = 0;
    scrollRef.value.addEventListener('mousedown', (event:any) => {
      isDragging.value = true;
      offsetX = event.clientX - contentRef.value.offsetLeft;
      offsetY = event.clientY - contentRef.value.offsetTop;
    }, { passive: false });
    
    scrollRef.value.addEventListener('mousemove', (event:any) => {
      if(importData.show) return 
      if (isDragging.value) {
        const x = event.clientX - offsetX;
        const y = event.clientY - offsetY;
        offsetX = event.clientX;
        offsetY = event.clientY
        wheelData.x1+= x;
        wheelData.y1+= y;
        getMatrix()
      }
    }, { passive: false });

    scrollRef.value.addEventListener('mouseup', () => {
      isDragging.value = false;
    }, { passive: false });
    window.addEventListener('keydown', (event:any) => {
      if (event.key === ' ') {
        spaceDown.value = true; 
      }
    }, { passive: false });
    window.addEventListener('keyup', (event:any) => {
      if (event.key === ' ') {
        spaceDown.value = false;
      }
    }, { passive: false });
  }
  
  if(is_mobile){
    initGestureHandlers();
  }
  
  
});

</script>

<style lang="scss" scoped>
  .inner{
    position: absolute; display: flex; align-items: center; justify-content: center;
    img{max-width: 100%; max-height: 100%; display: block;}
  }
  .mobileBox{
    .name1{font-size: 12px;}
    .header{padding:6px 10px;}
    .header-content-box{height:42px;}
    :deep(.el-page-header__left){
      margin-right:0px;
      .el-page-header__back, .el-divider{display: none;}
    }
  }
  #scroll2{
    transform-origin: left top; position: fixed; left: 200%; top:55px; z-index: 30;
    .myCanvas-box{
      background-color: #fff;
      &.import-text{transform: scaleY(-1) !important; }
    }
  }
  #scroll{
    .myCanvas-box{
      transform-origin: left top; 
    }
  }
  .dot{position: absolute; width: 90px; height:90px; background-color: red; left: 2299px; top:272px}
  .searchShow{
    position: fixed; width: 160px; height: 100vh; left:0; top:0; z-index:30; background-color: #fff; box-shadow: 0 2px 10px #ddd; padding-top: 60px;
    .el-drawer__header{padding: 10px;}
    .search-item{
      padding: 8px 10px;
      &.on{background-color:var(--el-color-primary-light-9);}
    }
    &.is_mobile{
      width:100%;padding-top:0; height:auto;
      .search-item{display:inline-block;}
    }
  }
  .hebItem{
    &.on1 .clip {
      background-color:#e4e5ff;
    }
    &.on .clip{background-color: #89abff;}
  }
  .zhua{
    cursor: grab;
    .hebItem{cursor: grab;}
  }
  .nobg{
    .hebItem{
      .clip{width: 100%; height: 100%; left: 0px; top:0px; background-color: rgba(255, 255, 255, 1);z-index:2; position: absolute;}
      .clip-black{ background-color: #000;}
      *{color: #000}
    }
  }
  .normal{
    .hebItem {
      transition: all ease 0.05s;
      &:hover{transform: scale(1.5); z-index: 999999;}
    }
  }
  .havePath {
    :deep(.el-page-header__left){display:none}
  }
  :deep(.el-page-header__content){font-size: 14px; flex:1; width:100%}
  :deep(.el-page-header__left){flex:1; width:100%}
  :deep(.el-icon){margin-right: 6px;}
  :deep(.zbselect){
    width:100%; height:100%; left:0; top:0; opacity: 0; position: absolute !important;
  }
  :deep(.zb-checkbox){
    right: 0px; top: 0px; position: absolute !important; padding-right: 10px;
    .el-checkbox__inner{border-radius: 50% !important;}
  }
  .no-select { user-select: none; }
  .header {
    background-color: #fff; padding: 10px 20px;
    height: 55px; box-shadow: 1px 1px 6px #ddd; position: relative; z-index:40;
    width: 100%;
    .list{
      .block{
        width: 90px; height:30px; background-color: #F5F5F5; border-radius: 4px; padding-left: 8px; outline: none; border: none; padding-left: 30px;
        &.w1{width: 120px;}
      }
      .s{position: absolute; left:8px ; display: block; line-height: 30px;}
      .lab{width: 60px; line-height: 30px;}
      .item{margin-right: 20px;}
    }
  }

  
  
  .canvas-box {
    width: 100%;
    height: 100vh;
    background-color: #ddd ;
    .myCanvas-box{
      position: absolute; left: 0; top: 0; 
      &.ease{transition: all ease 0.1s;}
      // transform-origin: 0 0;
      .myCanvas-box-div{
        // position: absolute; transform-origin: left top; 
      }
    }
    .scroll{
      width: 100vw;
      height: calc(100vh - 60px);
      overflow:hidden; position: relative;            
    }
    

    #myCanvas {
      position: absolute; box-sizing: border-box;box-shadow: 0 0 2px red; transform-origin: 0 0;
      z-index: 2; left:0; top:0; width: 100%; height: 100%;
    }
  }
 
</style>